相关疑难解决方法(0)

构造函数中这个奇怪的冒号成员(":")语法是什么?

最近我见过如下例子:

#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++书中找到它吗?

c++ syntax constructor c++-faq ctor-initializer

325
推荐指数
11
解决办法
10万
查看次数

我看到了这个节目.这是什么 - 在构造函数复数(double r,double i)之后的re(r),im(i){}?

// operator_overloading.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

struct Complex {
   Complex( double r, double i ) : re(r), im(i) {} // what is this syntax?
   Complex operator+( Complex &other );
   void Display( ) {   cout << re << ", " << im << endl; }
private:
   double re, im;
};

// Operator overloaded using a member function
Complex Complex::operator+( Complex &other ) {
   return Complex( re + other.re, im + other.im );
}

int main() { …
Run Code Online (Sandbox Code Playgroud)

c++ syntax

-4
推荐指数
1
解决办法
377
查看次数

标签 统计

c++ ×2

syntax ×2

c++-faq ×1

constructor ×1

ctor-initializer ×1