質問するログイン新規登録
C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

Q&A

解決済

2回答

899閲覧

構造体を使ったヘッダファイルの書き方がわからない

langhtorn

総合スコア105

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

0グッド

0クリップ

投稿2023/08/19 15:41

0

0

質問事項

ヘッダファイル内で定義したクラスの変数の扱い方がわかりません.

プログラム

ヘッダファイルheader_practice.hppの中身をheader_practice.cppにて定義しています.最終的に実行したいプログラムはhp.cppです.

c++

1//header_practice.cpp 2// ヘッダーファイルの書き方テンプレ 3 4#include<iostream> 5#include "header_practice.hpp" 6 7using namespace std; 8 9void say(){ 10 cout<<"Hello!"<<endl; 11} 12 13struct Point{ 14 double x,y; 15}; 16 17void p_print(Point p){ 18 cout<<p.x<<","<<p.y<<endl; 19} 20 21int main() 22{ 23 Point p; 24 cin>>p.x>>p.y; 25 say(); 26 p_print(p); 27}

c++

1//header_practice.hpp 2class hp{ 3 public: 4 5 struct Point 6 { 7 double x,y; 8 }; 9 10 11 void say(); 12 void p_print(Point p); 13};

c++

1//hp.cpp 2#include<iostream> 3#include "header_practice.hpp" 4 5using namespace std; 6 7struct Point{ 8 double x,y; 9}; 10 11int main() 12{ 13 Point p; 14 hp hdp; 15 cin>>p.x>>p.y; 16 hdp.say(); 17 hdp.p_print(p); 18}

エラー
コンパイルした結果定義したクラスの変数を扱うことができませんでした.どのようにしたら扱うことができるようになるのか教えていただきたいです.

hp.cpp: In function ‘int main()’: hp.cpp:16:17: error: cannot convert ‘Point’ to ‘hp::Point’ 16 | hdp.p_print(p); | ^ | | | Point In file included from hp.cpp:2: header_practice.hpp:11:24: note: initializing argument 1 of ‘void hp::p_print(hp::Point)’ 11 | void p_print(Point p); | ~~~~~~^

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2023/08/19 19:41

struct Point が class hp の中に書いてあるから、かな。
guest

回答2

0

Point の定義をclassの外に出しましょう

投稿2023/08/19 22:13

y_waiwai

総合スコア88180

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

langhtorn

2023/08/20 03:51

回答ありがとうござます!
guest

0

ベストアンサー

次のように書いてください。

C++

1//header_practice.cpp 2// ヘッダーファイルの書き方テンプレ 3 4#include <iostream> 5#include "header_practice.hpp" 6 7using namespace std; 8 9void hp::say() { 10 cout << "Hello!" << endl; 11} 12 13void hp::p_print(Point p) { 14 cout << p.x << "," << p.y << endl; 15}

C++

1// hp.cpp 2#include<iostream> 3#include "header_practice.hpp" 4 5using namespace std; 6 7int main() 8{ 9 hp::Point p; 10 hp hdp; 11 cin >> p.x >> p.y; 12 hdp.say(); 13 hdp.p_print(p); 14}

投稿2023/08/19 22:19

編集2023/08/19 22:22
kazuma-s

総合スコア8222

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

langhtorn

2023/08/20 03:50

できました.ありがとうござます!
kazuma-s

2023/08/20 11:53

「できました」というのは「理解できた」ということですか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.30%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問