嵌套类构造有关问题
嵌套类构造问题#include stdafx.h#include string#include iostreamusing namespace stdclass CSub
嵌套类构造问题
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class CSub
{
public:
CSub();
CSub(string name);
~CSub();
public:
string m_subName;
int m_subAge;
};
CSub::CSub()
{
m_subName = "树根";
m_subAge = 10;
}
CSub::CSub(string name)
{
m_subName = name;
m_subAge = 20;
}
CSub::~CSub()
{
}
class CSuper
{
public:
CSuper();
~CSuper();
CSub* GetSub(){return &m_sub;}
private:
string m_superName;
int m_superAge;
CSub m_sub;
};
CSuper::CSuper()
{
m_superName = "桦树";
m_superAge = 100;
m_sub = CSub::CSub("树叶"); //这一行,如果去掉,编译器会自动调用默认构造函数
//我想知道,对m_sub进行初始化还有其他方法吗?
}
CSuper::~CSuper()
{
}
int main(int argc, char* argv[])
{
CSuper superOne;
cout<<"名称: " << superOne.GetSub()->m_subName<<endl;
cout<<"年龄: "<< superOne.GetSub()->m_subAge<<endl;
system("pause");
return 0;
}
[解决办法] m_sub = CSub::CSub("树叶"); //这一行,如果去掉,编译器会自动调用默认构造函数
//我想知道,对m_sub进行初始化还有其他方法吗?
你这样写不对呀,这样会让m_sub构造两次呀.正确的写法是:
CSuper::CSuper():m_sub("树叶")
{
}
建议楼主仔细看下 c++ primer
[解决办法]构造函数只是形式上没有返回值。
实际上,构造函数是有返回值的,返回被构造对象本身。
就是返回构造的结果。
你见过这么写构造函数的么?
void CSub::CSub(cost char* ){};
没有吧!
相对的,析构函数,倒是真的没有返回值。
构造函数可以看作:
CSub & CSub::CSub(cost char* ){};
这种形式。
析构就是这种形式:
void CSub::~CSub(void){}
[解决办法]也许你的编译器能编过。但gcc不行。
[解决办法]=== test_console, Debug ===
[解决办法]***/main.cpp
[解决办法]In constructor ‘CSuper::CSuper()’:
[解决办法]***/main.cpp
[解决办法]238
[解决办法]error: cannot call constructor ‘CSub::CSub’ directly [-fpermissive]
[解决办法]***/main.cpp
[解决办法]238
[解决办法]error: for a function-style cast, remove the redundant ‘::CSub’ [-fpermissive]
[解决办法][解决办法]=== Build finished: 2 errors, 0 warnings (0 minutes, 1 seconds) ===
[解决办法]