如何通过运算符<<的重载访问受保护的功能?C++
How to access to a protected function with the overloading of the operator << ? C++
对于C++练习,我必须在使运算符重载<<的函数中使用受保护的 c++。
但是我们知道,如果我们想在 cpp 文件中定义函数,可以在类中或使用关键字 friend 访问受保护的函数。
目前,我有一个抽象类和主要类。
我不知道如何修复此错误,我想尽早完成此练习;)
卡.hpp
#ifndef CARD_HPP
#define CARD_HPP
#include <string>
#include <iostream>
class Card
{
std::string name;
protected:
virtual std::ostream & toStream(std::ostream & out){out << name;return out;}
public:
Card(std::string n):name(n){}
friend std::ostream & operator<<(std::ostream & out, const Card &c);
};
#endif
卡.cpp
#include <Card.hpp>
std::ostream & operator<<(std::ostream & out, const Card &c)
{
return c.toStream(out);
}
主.cpp
#include <Card.hpp>
using namespace std;
int main()
{
Card card("montain");
cout << card << "n";
return 0;
}
输出
clang++ -Wall -std=c++14 -c -o obj/main.o src/main.cpp -I include
clang++ -Wall -std=c++14 -c -o obj/Card.o src/Card.cpp -I include
src/Card.cpp:5:12: error: member function 'toStream' not viable: 'this' argument has type 'const Card', but function is not
marked const
return c.toStream(out);
^
include/Card.hpp:12:32: note: 'toStream' declared here
virtual std::ostream & toStream(std::ostream & out){out << name;return out;}
^
1 error generated.
makefile:16: recipe for target 'obj/Card.o' failed
make: *** [obj/Card.o] Error 1
生成文件
CC = clang++
CFLAGS = -Wall -std=c++14
HDIR = include
ABSTRACT = obj/Card.o
.PHONY: doc
compile: bin/main
./bin/main
bin/main: obj/main.o ${ABSTRACT}
${CC} ${CFLAGS} -o $@ $^
obj/%.o: src/%.cpp
${CC} ${CFLAGS} -c -o $@ $< -I ${HDIR}
doc:
doxygen Doxyfile
clean:
rm obj/*.o
rm bin/*
cleanDoc:
rm doc/* -rf
问题不在于该功能受到保护,而在于它不const
。
src/Card.cpp:5:12: error: member function 'toStream' not viable: 'this' argument has type 'const Card', but function is not marked const return c.toStream(out);
正如错误消息所说,由于const Card &c
,c
const
,并且您只能在c
上调用 const 成员函数。
因此,要么将toStream
成员函数设置为const
:
virtual std::ostream & toStream(std::ostream & out) const
或者更改流式处理运算符,以便c
不是常量。但不建议这样做,如果函数需要更改/替换传递的参数,则只应作为非常量引用传递:
std::ostream & operator<<(std::ostream & out, Card &c)
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- <<操作员在下面的行中工作
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符