相关疑难解决方法(0)

C++创建对象,初始化列表与赋值?

我最近和一位朋友讨论过他们说当你在C++中创建对象时使用初始化列表(而不是简单地分配数据成员)时会有性能提升.

为什么这样(如果是真的)?

我找到了这个页面:

http://www.parashift.com/c++-faq/init-lists.html

他们提到临时对象,但我想最近的编译器可以避免这种情况?

c++ performance

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

哪两个会更快地初始化一个对象?

class A {
   public:
   int a;
   A(int x)
   {
      a = x;
   }
};
Run Code Online (Sandbox Code Playgroud)

要么

class B {
       public:
       int b;
       B(int x):b(x){}
};
Run Code Online (Sandbox Code Playgroud)

哪一个会更快地初始化对象?或者最终会为两者生成相同的代码,初始化所需的时间将保持不变?或者它取决于编译器?

c++

3
推荐指数
1
解决办法
484
查看次数

使用自定义构造函数将对象实例化为类属性 (C++)

我正在使用 C++ 编写一个标准的战舰游戏,其中包含一个 Game 对象,其中包含两个 Player 对象。当我尝试在 Game 构造函数中实例化 Player 对象时,IntelliSense 给出两个错误:

IntelliSense:表达式必须是可修改的左值

IntelliSense:不存在合适的构造函数可从“Player ()”转换为“Player”

这是我的头文件:

class Player {
public:
    Player(string name);
    //More unrelated stuff (Get/Set methods and Attributes)
};


class Game {
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);
    //Get and Set methods (not included)
    //Attributes:
    Player Player1();
    Player Player2();
    int turn;
};
Run Code Online (Sandbox Code Playgroud)

我对 Player 构造函数的定义:

Player::Player(string name)
{
    SetName(name);
    //Initialize other variables that don't take input
{
Run Code Online (Sandbox Code Playgroud)

以及给出错误的代码:

//Game constructor
Game::Game(bool twoPlayer, string Player1Name, string Player2Name)
{
    Player1 …
Run Code Online (Sandbox Code Playgroud)

c++ constructor class object

3
推荐指数
1
解决办法
7078
查看次数

标签 统计

c++ ×3

class ×1

constructor ×1

object ×1

performance ×1