有关类继承的C ++编译问题

时间:2019-03-10 02:32:24

标签: c++ inheritance

由于我是继承人中的新手,所以遇到了一些编译错误,我不知道该如何解决。我无处可去,因此我来了。我的'='赋值运算符也是错误的,只是我没有要显示的复杂错误。如果有人可以帮助我,我将不胜感激。谢谢!

编译错误:

 main.cpp: In function ‘std::ostream& operator<<(std::ostream&, Line&)’:

 main.cpp:56:17: error: no match for ‘operator<<’ (operand types are 

 ‘std::basic_ostream<char>’ and ‘Point’)
 stream << "(" << p.p1 << ", " << p.p2 << ")" << endl;
 ~~~~~~~~~~~~~~^~~~~~~

 In file included from /usr/lib/gcc/x86_64-pc- 
 cygwin/7.4.0/include/c++/iostream:39:0,
             from main.cpp:1:
 /usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/ostream:108:7: note: 
 candidate: std::basic_ostream<_CharT, _Traits>::__ostream_type& 
 std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, 
 _Traits>::__ostream_type& (*)(std::basic_ostream<_CharT, 
 _Traits>::__ostream_type&)) [with _CharT = char; _Traits = 
 std::char_traits<char>; std::basic_ostream<_CharT, _Traits>::__ostream_type 
 = std::basic_ostream<char>]
   operator<<(__ostream_type& (*__pf)(__ostream_type&))
   ^~~~~~~~

Main.cpp

class Point
{
private:
    int x, y;
public:
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}


};

class Linee : public Point 
{ 
 private:
    Point p1;
    Point p2;
public:
    Line(const Point & p1, const Point & p2 ) : p1(p1), p2(p2) {}

    friend ostream &operator<<(ostream &stream, Line &p);
    Line& operator = (const Line &a);       
    void Draw();

};

ostream &operator<<(ostream &stream, Line &p) {
    stream << "(" << p.p1 << ", " << p.p2 << ")" << endl;
    return stream;
}

Line& operator = (const Line &a)
{
    p1 = a.p1;
    p2 = a.p2;
    return *this;
}
    void Line::Draw() {
cout << "Line" << "drawing" << endl;
}

int main() 
{
Line l1;                //Output: Line construction
std::cout << l1;        //Output: Line (0,0) (0,0)
l1.Draw();              //Output: Line drawing

Line l2(Point(), 
Point(100,100));    //Output: Line construction
std::cout << l2;        //Output: Line (0,0) (100,100)
l1 = l2;
std::cout << l1;        //Output: Line (0,0) (100,100)
}

1 个答案:

答案 0 :(得分:0)

stream << "(" << p.p1 << ", " << p.p2 << ")" << endl;

由于p.p1p.p2的类型为Point,因此只有在Point实现适当的operator<<的情况下,此代码才能工作。显然不是。

尝试指向(hehe)到打印x的{​​{1}}或y坐标的代码。您无法执行此操作,因为没有这样的代码。