【问题标题】:C++ request for member ‘’ in ‘’, which is of non-class type ‘’ [duplicate]C ++请求''中的成员'',它是非类类型'' [重复]
【发布时间】:2017-12-03 19:48:19
【问题描述】:

我写了一个简单的C++程序,如下-

#include<iostream>
using namespace std;

class Rectangle
{
    double length, breadth;

public:
    Rectangle(void);        // constructor overloading
    Rectangle(double, double);  // constructor of class
    // void set_values(double l, double b);
    double area(void);
};  // can provide an object name here


// default constructor of class 'Rectangle'-
Rectangle::Rectangle(void)
{
    length = 5;
    breadth = 5;
}


// constructor of class 'Rectangle'-
Rectangle::Rectangle(double l, double b)
{
    length = l;
    breadth = b;
}


/*
void Rectangle::set_values(double l, double b)
{
    length = l;
    breadth = b;
}
*/


double Rectangle::area(void)
{
    return length * breadth;
}


int main()
{
    /*
    Rectangle r;
    r.set_values(12, 3.4);
    */

    Rectangle r(12, 3.4);
    Rectangle s();

    cout<<"Area = "<<r.area()<<endl;
    cout<<"Area = "<<s.area()<<endl;


return 0;
}

当我尝试编译它时,我收到以下错误-

Classes_Example.cpp: In function ‘int main()’:
Classes_Example.cpp:61:21: error: request for member ‘area’ in ‘s’, which is of non-class type ‘Rectangle()’
  cout<<"Area = "<<s.area()<<endl;

我正在使用 g++ (GCC) 7.2.0

谢谢!

【问题讨论】:

  • Rectangle s(); 是一个函数声明。
  • Most vexing parse。我们真的需要一个规范的问答条目。我很惊讶我找不到。
  • Rectangle s(); 声明了一个名为 s 的函数,它不接受任何参数并返回一个 Rectangle。这被称为 C++ 中最令人头疼的解析。将其更改为 Rectangle s; 或 Rectangle s{};。
  • @Cornstalks,我也在想同样的事情。
  • 您应该始终使用list initialization。大多数令人烦恼的解析没有问题只是它的好处之一。

标签: c++


【解决方案1】:
Rectangle s();

是一个函数声明而不是变量。在 c++ 中,任何可以被解析为函数声明的东西都将解析变量替代。删除 () 将使其成为变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    相关资源
    最近更新 更多