C++类基本--随笔二

 1 #include <iostream>
 2 #include <string.h>
 3 using namespace std;
 4 
 5 class Internet
 6 {
 7 public:
 8     Internet()
 9     {
10 
11     };
12     Internet(char *name,char *address)
13     {
14         cout<<"载入构造函数"<<endl;
15         strcpy(Internet::name,name);
16     }
17     Internet(Internet &temp)
18     {
19         cout<<"载入COPY构造函数"<<endl;
20         strcpy(Internet::name,temp.name);
21         cin.get();
22     }
23     ~Internet()
24     {
25         cout<<"载入析构函数!";
26         cin.get();
27     }
28 protected:
29     char name[20];
30     char address[20];
31 };
32 Internet tp()//这不是函数,是对象!!!!!!!!
33 {
34     Internet b("中国软件开发实验室","www.cndev-lab.com");
35     return b;
36 }
37 int main()
38 {
39     Internet a;
40     a=tp();  //注意下面结果。没有拷贝构造函数,  //这样赋值?不算拷贝???? }
41 }

//调用析构函数2次,是因为函数返回有个temp临时对象,返回的是临时对象!!!

#include <iostream>
#include <string.h>
#include <string>
using namespace std;

class Internet
{
public:
    Internet(char *name,char *address)
    {
        cout<<"载入构造函数"<<endl;
        strcpy(Internet::name,name);
    }
   Internet(const Internet &temp)  //再用匿名对象/无名对象  时,必须加const ,否则编译器报错 (gcc)
    {
        cout<<"载入COPY构造函数"<<endl;
        strcpy(Internet::name,temp.name);
        cin.get();
    }
    ~Internet()
    {
        cout<<"载入析构函数!";
    }
public:
    char name[20];
    char address[20];
};

int main()
{
     Internet a=Internet("中国软件开发实验室","wwwv");
 //Internet &a=Internet("中国软件开发实验室","wwwv");   错误
 //匿名对象是一种临时对象,一般来说在该行代码之后都马上析构的,这样的东西编译器是把它看作右值的,右值是不能引用的 
 cout<<a.name; 
cin.
get();
}
原文地址:https://www.cnblogs.com/qbmiller/p/3804053.html