最近我见过如下例子:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这奇怪: bar(num)意味着什么?它似乎初始化成员变量,但我以前从未见过这种语法.它看起来像一个函数/构造函数调用,但对于一个int?对我没有任何意义.也许有人可以启发我.而且,顺便说一下,还有其他类似的深奥语言功能,你永远不会在一本普通的C++书中找到它吗?
我使用Borland C++ Builder.
我有问题
#include <Classes.hpp>
class TMyObject : public TObject
{
__fastcall TMyObject();
__fastcall ~TMyObject();//I would like to inherite my destructor from TObject
};
__fastcall TMyObject::TMyObject() : TObject()//it will inherited my constructor from TObject
{
}
Run Code Online (Sandbox Code Playgroud)
对于那个将继承的新析构函数~TObject?
__fastcall TMyObject::~TMyObject?????????????
Run Code Online (Sandbox Code Playgroud) 基本上,我有一个名为VisaMux的类和一个名为MuxPath的类.MuxPath有一个VisaMux私有实例变量.我希望MuxPath的构造函数在不调用空的VisaMux()构造函数的情况下为给定的VisaMux对象分配实例变量.
5 MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux){
6 clk_sel = Clk_sel;
7 lane_sel = Lane_sel;
8 mux = Mux;
9 }
Run Code Online (Sandbox Code Playgroud)
此代码导致错误:
MuxPath.cpp:5: error: no matching function for call to ‘VisaMux::VisaMux()’
VisaMux.h:20: candidates are: VisaMux::VisaMux(const std::string&, const uint&, const uint&, const std::vector<VisaLane, std::allocator<VisaLane> >&, const std::vector<VisaResource, std::allocator<VisaResource> >&)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的那样,它在第一行(第5行)出错,所以似乎某些const VisaMux&Mux正在调用不存在的VisaMux().如果我只使用VisaMux Mux,也会发生这种情况.
我不希望它为VisaMux调用一个空的构造函数,因为我希望只通过传递构造函数所有必需的参数来创建VisaMux.
我怎样才能做到这一点?
我在初始化对象时遇到问题.以下是一段代码,
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
Base(int a)
{
m_a = a;
}
private:
int m_a;
};
class Derived:public Base
{
public:
Derived(char a)
{
m_a = a;
}
private:
char m_a;
};
void main()
{
_getch();
}
Run Code Online (Sandbox Code Playgroud)
编译上面的代码会出现以下错误,错误C2512:'Base':没有合适的默认构造函数可用
我知道由于派生类和基类都只有参数化构造函数,我需要在派生类构造函数中初始化基类对象.但我不知道该怎么做.谁能告诉我上面的代码有什么问题?