小编J. *_*Lin的帖子

C++类访问级别

假设我有两个班级.一个叫Point:

class Point{
    public:
        Point(): x_(0), y_(0) {}
    protected: 
        int x_, y_;
    };
Run Code Online (Sandbox Code Playgroud)

然后我有另一个类,它派生自Point:

class Point3D : public Point {
public:
    Point3D(): Point(), z_(0){}
    double distance(Point3D pt, Point base) const;
protected:
    int z_;
};

double Point3D::distance(Point3D pt, Point base) const
{
    int dist_x, dist_y;
    dist_x = base.x_ - x_;
    dist_y = base.y_ - y_;

    return sqrt(dist_x * dist_x +
                dist_y * dist_y);
}
Run Code Online (Sandbox Code Playgroud)

然后我得到了如下错误:base.x_在此上下文中受到保护.但Point3D到Point的访问级别是公共的,并且Point中的x_ data成员受到保护.所以它应该没有错误,对吧?有人可以帮我解决这个问题吗?

c++ inheritance

9
推荐指数
1
解决办法
194
查看次数

在c ++中的不同目录中包含头文件

我一直在学习c ++并遇到了以下问题:我有一个目录结构,如:

 - current directory

  - Makefile

  - include

     - header.h

  - src

      - main.cpp
Run Code Online (Sandbox Code Playgroud)

我的header.h:

#include <iostream> 

using namespace std;

void print_hello();
Run Code Online (Sandbox Code Playgroud)

我的main.cpp:

#include "header.h"

int main(int argc, char const *argv[])
{
    print_hello();
    return 0;
}

void print_hello()
{
    cout<<"hello world"<<endl;
}
Run Code Online (Sandbox Code Playgroud)

我的Makefile:

CC = g++
OBJ = main.o
HEADER = include/header.h 
CFLAGS = -c -Wall 

hello: $(OBJ) 
    $(CC) $(OBJ) -o $@

main.o: src/main.cpp $(HEADER)
    $(CC) $(CFLAGS) $< -o $@

clean: 
    rm -rf *o hello
Run Code Online (Sandbox Code Playgroud)

而make的输出是:

g ++ -c …

c++ makefile

7
推荐指数
2
解决办法
3万
查看次数

标签 统计

c++ ×2

inheritance ×1

makefile ×1