【问题标题】:No appropriate default constructor available - Visual Studio没有合适的默认构造函数可用 - Visual Studio
【发布时间】:2014-06-23 00:29:29
【问题描述】:
#include <iostream>
#include <stdlib.h>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';
  delete bar;
  delete[] baz;
  system("PAUSE");
  return 0;
}

此代码在代码块中执行,但在 Visual Studio 中,没有可用的适当默认构造函数。

我尝试在这里搜索类似的东西,但我找不到任何东西。

【问题讨论】:

  • 您没有默认构造函数。如果您发布整个错误并显示它抱怨的行,您可能会得到答案。
  • baz = new Rectangle[2] { {2,5}, {3,6} }; 可能会给您一些关于默认构造函数的编译器问题。
  • 您拥有哪个版本的 Visual Studio 以及您将哪个编译器/版本与代码块一起使用(代码块不是编译器;它是一个开发环境,可以与不同的编译器一起使用)?
  • 另外,当询问涉及编译器错误的问题时,请准确地引用错误

标签: c++ arrays class pointers default-constructor


【解决方案1】:

operator newoperator new[] 以及将参数传递给新建元素的构造函数的方式有所不同。

例如:(取自维基百科略有修改的版本)

T *p = new T(42); //New T inited to T(42). (same syntax as constructors)
T *parray = new T[42];  //An array of 42 T, inited with T()
T *cpp11array = new T[3] {1, 2, 3};  //3 Ts, inited to T(1), T(2) and T(3) (C++11 only)

看来您的 Visual Studio C++11 兼容。希望应该有启用 C++11 std 的选项,或者您可能想要安装最新的编译器。

作为旁注,您应该更喜欢 STL 容器(例如:std::array 或 std::vector 而不是裸指针数组)。

vector<Rectangle> baz;
baz.push_back( Rectangle(2, 5) );
baz.push_back( Rectangle(3, 6) );

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2016-01-22
    • 1970-01-01
    • 2022-11-01
    • 2013-03-20
    相关资源
    最近更新 更多