C++ 中的一些错觉

1.

默认构造函数和不带参数的构造函数之间无联系

默认构造函数是编译器发现类不存在显式构造函数时自动生成的无参数的构造函数。同样,用户可以定义显示的无参数构造函数。

2.

在构造函数、析构函数中调用virtual 函数。并不会得到预期的结果。virtual函数在此时会"丢失"virtual性质。

3.

构造函数无参数的时候

 1 #ifndef UNTITLED2_TEST_H
 2 #define UNTITLED2_TEST_H
 3 
 4 #include <stdio.h>
 5 class test {
 6 public:
 7     test()
 8     {
 9         printf("call test()\n");
10     }
11     test(char c)
12     {
13         printf("call test(char)");
14     }
15 };
16 
17 
18 #endif //UNTITLED2_TEST_H
1 #include "test.h"
2 int main() {
3     test t;//申明一个变量
4     test tt();//声明一个函数。
5     test tc('c'); //申明一个变量
6     return 0;
7 }
/Users/like1/CLionProjects/untitled2/cmake-build-debug/untitled2
call test()
call test(char)
Process finished with exit code 0

test t();并不会像test t;调用test::test()构造函数,仅仅是申明了一个函数,返回类型是test,无参数,函数名是t。

4.

test tc = t;

test* t = &tc;

并不会调用operator=(test& t);而是调用test(test& t);

5.

new delete 和 malloc() free() 的行为存在共性,但不等价。

new 和 delete 会在分配内存后调用类的构造函数,析构函数。

6.

test t;
test tt = t;

这样的定义语句不一定正确。

#ifndef UNTITLED2_UN_COPY_ASSIGN_H
#define UNTITLED2_UN_COPY_ASSIGN_H


class un_copy_assign {
public:
    un_copy_assign();
private:
    un_copy_assign(un_copy_assign& c);
    un_copy_assign& operator=(un_copy_assign& c);
};


#endif //UNTITLED2_UN_COPY_ASSIGN_H
#ifndef UNTITLED2_TEST_H
#define UNTITLED2_TEST_H

#include "un_copy_assign.h"
#include <stdio.h>
class test : public un_copy_assign{
public:
    test():un_copy_assign()
    {
        printf("call test()\n");
    }
    test(char c):un_copy_assign()
    {
        printf("call test(char)");
    }
};


#endif //UNTITLED2_TEST_H

 

 

http://www.cnblogs.com/like1/p/6852528.html 

posted @ 2017-05-14 15:03  ZHRYlike1  阅读(279)  评论(0编辑  收藏  举报