ℬ悟透C++┇Puzzle记录

Posted itzyjr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ℬ悟透C++┇Puzzle记录相关的知识,希望对你有一定的参考价值。

C++ Puzzles
★1.有如下代码,问:ptr指向了谁?能通过ptr调用Derived类重写的函数吗(即多态还起作用吗)?dynamic_cast到底是什么作用?ptr2与ptr性质是一样的吗?

Derived* derived = new Derived();
Base *ptr = dynamic_cast<Base*>(derived);
Base *ptr2 = (Base*) derived;

★2.如下代码,将一个类对象直接转换成了int类型,并且成功了,原因是什么?显示的构造函数成为的转换函数与直接定义的准转换函数之间有什么核心区别?

// matStep是一个类对象
bool b = static_cast<int>(matStep);// b == true

★3.如下代码,在.cpp文件中需要对.h文件中声明的类类型成员变量写判空逻辑有必要吗?通过“obj == nullptr”这个表达式来判断有什么问题?Robot的两个私有成员变量在对象初始化时的值分别是什么?

// test.h
class Robot 
public:
	void startup();
private:
	float precise;
	QPixMap pixmap;
...

// test.cpp
void Robot::startup() 
	if (!pixmap.isNull()) ...// use directly?
	if (pixmap == nullptr) ...// check if null first??

★4.定义了如下方法,为什么后面的代码使用没有毛病?

// definition
template<typename _Tp>
_Tp& cv::Mat::at(int i0 = 0)
// use
Mat H(100, 100, CV_64F);
for(int i = 0; i < H.rows; i++)
    for(int j = 0; j < H.cols; j++)
        H.at<double>(i,j)=1./(i+j+1);// can it be?

★5.如下代码为什么会出现“二义性”编译错误?

// file1: circle.h
#include <iostream>
std::string mark;// out of the class scope
class Circle 
public: Circle();

// file2: circle.cpp
#include "circle.h"
Circle::Circle() 

★6.全局和局部变量的生命周期有不同吗?下面代码,在调用并执行完dosomething()方法后,box1、box2、box3这三个对象还都存在吗?

class Circle 
public:
	Box box1;
	Box* box2;
	void dosomething();


void Circle::dosomething() 
	box1 = Box(10, 15);
	box2 = new Box(25, 35);
	Box box3 = Box(60, 70);
	// ...

★7.子类重写父类的protected方法,一定要定义在子类的protected域吗?可以定义在private域吗?可以定义在public域吗?
★8.如下代码为什么有问题?

// 首先mimeData()函数的原型如下:
inline const QMimeData *mimeData() const;
// 调用过程如下:
QMimeData* mimeData = event->mimeData();
报错:error: Cannot initialize a variable of type 'QMimeData *' with an rvalue of type 'const QMimeData *'

★9.如下代码,为什么出问题?该如何解决?

void test(char* outBuf) 
	...
	outBuf = new char[10];
	outBuf[0] = 123;

void main() 
	char* buffer;
	test(buffer);
	cout << buffer[0];// error occur!
	return 0;

★10.两种防卫式声明方式有什么区别?能随便互换使用吗?
最下面是一个报错示例。

--------1. 宏定义------------
#ifndef _FILENAME_
#define _FILENAME_
......
#endif
--------2. 编译器指令--------
#pragma once
......
--------报错示例-1-------------
报错:
[qenhancedlabel.h]
#pragma once
class QEnhancedLabel : public QLabel 
[mainwindow.h]
#pragma once
#include "qenhancedlabel.h"
class MainWindow : public QMainWindow 
private:
	QEnhancedLabel* vsectionLabal;

[ui_mainwindow.h]
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include "qenhancedlabel.h"
......
#endif
[mainwindow.cpp]// 注:是C++文件而非头文件
#pragma once// 本就不要在CPP文件中添加此编译器指令
#include "mainwindow.h"
#include "ui_mainwindow.h"// 报错于此行
error: redefinition of 'QEnhancedLabel'

修复方法:替换[qenhancedlabel.h]中的#pragma once为#ifndef形式
--------报错示例-2-------------
[mainwindow.h]
#pragma once// 报错于此行
error: File 'd:/xxx/MathFunc.h' modified since it was first processed
注:实例上"PI"是宏定义的一个常量,根本没有修改它。
#include "MathFunc.h"
void afuction() 
	float vangle = vRotateAngle * PI / 180.0;

[MathFunc.h]
#pragma once
#define PI  3.141592653589793f

修复方法:替换p[MathFunc.h]中的#pragma once为#ifndef形式

★11.下面代码中,函数声明后缀 “&&”与“const &”是什么含义?

QImage QImage::rgbSwapped() &&
QImage QImage::rgbSwapped() const &

★12.下面代码中constexpr关键字是什么含义?可以随意用吗?

constexpr int max_files = 20;
constexpr int new_sz()  return 42; 
constexpr int foo = new_sz();
#Qt中<QPoint>头文件源码中有个方法,如下:
constexpr inline int QPoint::y() const noexcept 
    return yp;

#Qt中<QSizePolicy>头文件源码中有个构造方法,如下:
constexpr QSizePolicy(int i) noexcept : data(i)  

13.如下是某个类的说明,override表达什么意思?前面的virtual又是想对程序员表明什么?
什么情况下,会有最下面的警告(not error)产生?

警告(warning):E:\\workplaces\\xxx\\CustomDrawItem.h:43: warning: ‘type’ overrides a member function but is not marked ‘override’
★14.如下代码中,default关键字是什么作用?它可以随意用吗?

class Test
public:
    Test();
    Test(int a):x(a);
    Test(const Test& ts) =default;
    Test& operator=(const Test& ts) =default;
private:
    int x;
;

★15.如下代码中,delete关键字是什么作用?

class Test  
public: 
    Test(int a):x(a)  std::cout << x;  
    Test(double)=delete;
private:
    int x;
;

★16.以下代码中的参数具体是什么类型,可以传什么类型的参数?

QPixmap::QPixmap(const char *const [] xpm)

★17.对比下图中rx()、ry()与x()、y()的区别,在实际操作中,它们分别可以怎么操作,它们的用意有何不同?

★18.以下代码,两种实现的构造函数,对成员变量的初始化,有什么区别?

class MyClass 
public:
	MyClass(int i, int s);
private:
	int age;
	string name;

-----------------------------
MyClass(int i, string s) : age(i), name(s) 
MyClass(int a, string b) 
	age = a;
	name = b;
	

★19.以下函数中参数是引用类型,有什么好处?有哪些情况要避免这样使用?

bool CustomItemBase::isCornerSelected(int& index) 
    bool bSelect = false;
    index = 0;
    for (auto item : m_HandlesList) 
        if (item->getSelectState()) 
            bSelect = true;
            break;
        
        index++;
    
    return bSelect;

★20.以下代码的函数定义是什么意思?

// Element Class中的public成员函数
QPointF Element::operator QPointF() const

★21.传入到函数里面的引用(或指针),会在函数结束后自动被回收吗?下面代码中第1个函数中 img 局部变量在函数块结束后被析构,所以返回对象本身就是有问题的,对吗?第2个函数中,box 对象有意义吗?为什么?最最根本的原因是什么?第3个函数,为什么会导致程序运行不起来(Unhandled exception thrown:read access violation)?

Mat img2Mat(QImage& image) 
	QImage img = image.convertToFormat(Format_RGB888);
	return Mat(img.height(), img.width(), CV_8UC3, img.bits(), img.bytesPerLine());


void test(Box& box) 
	Box aBox;
	if (a > b)
		aBox = Box(w, h);
	else
		aBox = box123;
	box = aBox;


QImage mat2QImage(const cv::Mat* mat) 
    cv::Mat frame;
    cv::cvtColor(*mat, frame, cv::COLOR_BGR2RGB);
    return QImage(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);

★22.为什么函数声明中引用类型的参数加上const就可以直接传递临时变量,不加const就编译报错呢?底层机理是怎样的?

// Error version:::
void test(Box& box) ...
// 调用以上函数
test(Box(10,20));// Error:initial value of reference to non-const must be an lvalue

// OK version:::
void test(const Box& box) ...
test(Box(10,20));// All right!

★23.如下代码中用到了“前向声明”,为什么在编译时就不通过?

#include xxx
class Box;
struct Person 
	string name;
	int age;
	Person(Box* box) // use of undefined type
		box.show();
	

class Box 
public:
	int w;
	int h;
	show() 
		print("宽=" + w + ", 高=" + h);
	

★24.易错点,问:下面代码中 x 等于几?

bool isBook = true/false;
int x = 3 + isBook ? 5 : 9;
print(x);

★25.为啥下面第1、2行都有警告,第3行为什么能解决第1行的警告?第2 or 4行的警告怎么解决?

// Warning:Missing reference in range-for with non trivial type (QMap<QString, QVariant>) [clazy-range-loop-reference]
1.for (QMap<QString, QVariant> rowMap : results) 
	// Warning:allocating an unneeded temporary container [clazy-container-anti-pattern]
2.	indices << rowMap.values().at(0).toInt();

-----------------------------------------------------
3.for (const QMap<QString, QVariant>& rowMap : results)// Warning dispear!
4.	indices << rowMap.values().at(0).toInt();// how to do???

以上是关于ℬ悟透C++┇Puzzle记录的主要内容,如果未能解决你的问题,请参考以下文章

ℬ悟透C++┇Puzzle记录

ℰ悟透Qt┇Puzzle记录

ℰ悟透Qt┇Puzzle记录

ℰ悟透Qt┇Puzzle记录

ℱ悟透CMake┇Puzzle记录

ℯ悟透OpenCV┇Puzzle记录