首页 > 解决方案 > 关于类继承的 C++ 编译问题

问题描述

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

编译错误:

 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&))
   ^~~~~~~~

主文件

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)
}

标签: c++inheritance

解决方案


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

由于p.p1p.p2属于 类型Point,因此该代码只有在Point实现适当的operator<<. 它显然没有。

尝试指向(呵呵)打印 a 的xory坐标的代码Point。你不能这样做,因为没有这样的代码。


推荐阅读