开发者社区> 问答> 正文

没有默认构造函数的对象数组初始化

#include class Car { private: Car(){}; int _no; public: Car(int no) { _no=no; } void printNo() { std::cout<<_no<<std::endl; } }; void printCarNumbers(Car *cars, int length) { for(int i = 0; i<length;i++) std::cout<<cars[i].printNo(); }

int main() { int userInput = 10; Car *mycars = new Car[userInput]; for(int i =0;i < userInput;i++) mycars[i]=new Car[i+1]; printCarNumbers(mycars,userInput); return 0; }
我想创建一个汽车阵列,但出现以下错误:

cartest.cpp: In function ‘int main()’: cartest.cpp:5: error: ‘Car::Car()’ is private cartest.cpp:21: error: within this context 有没有办法在不使Car()构造函数公开的情况下进行此初始化? 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-09 13:35:43 436 0
1 条回答
写回答
取消 提交回答
  • 不。

    但是!如果您使用std::vector ,就应该使用(永远不要使用new[]),那么您可以确切指定元素的构造方式*。

    *很好。您可以指定要复制的值。

    像这样:

    #include #include

    class Car { private: Car(); // if you don't use it, you can just declare it to make it private int _no; public: Car(int no) : _no(no) { // use an initialization list to initialize members, // not the constructor body to assign them }

    void printNo()
    {
        // use whitespace, itmakesthingseasiertoread
        std::cout << _no << std::endl;
    }
    

    };

    int main() { int userInput = 10;

    // first method: userInput copies of Car(5)
    std::vector<Car> mycars(userInput, Car(5)); 
    
    // second method:
    std::vector<Car> mycars; // empty
    mycars.reserve(userInput); // optional: reserve the memory upfront
    
    for (int i = 0; i < userInput; ++i)
        mycars.push_back(Car(i)); // ith element is a copy of this
    
    // return 0 is implicit on main's with no return statement,
    // useful for snippets and short code samples
    

    } 带有附加功能:

    void printCarNumbers(Car *cars, int length) { for(int i = 0; i < length; i++) // whitespace! :) std::cout << cars[i].printNo(); }

    int main() { // ...

    printCarNumbers(&mycars[0], mycars.size());
    

    } 注意printCarNumbers确实应该以不同的方式设计,以接受两个表示范围的迭代器。

    2020-02-09 13:35:55
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载