我有一个类foo和bar.foo有资源.当bar从继承foo将它也有记忆的深层副本?或者我是否必须调用foofrom bardefault-constructor的构造函数?
class foo
{
char *item;
public:
foo() : item(new char[5]) {}
};
class bar : public foo {};
Run Code Online (Sandbox Code Playgroud) 我正在从结构C转向OOP C++,:在C++中声明/定义构造函数时,我经常发现" "符号作为运算符的特殊用法.我粗略地理解了这种风格的使用,但是有人用这个构造函数定义向我解释了精确的编程技术.
例如:1
class time_stamp
{
public:
time_stamp(time &t_time)
: m_time(t_time)
{}
~time_stamp()
{
m_time.update(); // as soon as I'm destroyed, update the time
}
private:
time &m_time;
};
Run Code Online (Sandbox Code Playgroud)
例如:2
class threaded_class
{
public:
threaded_class()
: m_stoprequested(false), m_running(false)
{
pthread_mutex_init(&m_mutex);
}
~threaded_class()
{
pthread_mutex_destroy(&m_mutex);
}
/** Some other member declarations */
}
Run Code Online (Sandbox Code Playgroud)
请解释我:在以下2个例子time_stamp(time &t_time) : m_time(t_time){}和下面的代码行中使用" "
threaded_class(): m_stoprequested(false), m_running(false)
{
pthread_mutex_init(&m_mutex);
}
Run Code Online (Sandbox Code Playgroud) 有没有办法将基类的私有成员变量设置为派生类的构造函数中的值?
我理解这是getter和setter方法的用途以及变量受保护或公共的用途,但假设您无法修改基类,是否有其他方法可以设置它?
如果我理解正确,则始终使用创建派生类的对象来调用基类构造函数.有没有办法在创建派生对象时调用重载的基类构造函数?
我正在尝试这个构造函数代码,并对它的工作方式感到困惑.
#include<iostream>
using namespace std;
class XYZ{
int a,b;
public:
XYZ(int i, int j):a(i), b(a*j){}
void show(){
cout<<a<<"\t"<<b<<"\n";
}
};
int main(){
XYZ X(2,3);
X.show();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了预期的结果,但是,
#include<iostream>
using namespace std;
class XYZ{
int b,a;
public:
XYZ(int i, int j):a(i), b(a*j){}
void show(){
cout<<a<<"\t"<<b<<"\n";
}
};
int main(){
XYZ X(2,3);
X.show();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
出乎意料的结果.
唯一的区别是int a,b和int b,a
以及如何XYZ(int i, int j):a(i), b(a*j){}正常工作?