EDIT: thanks for all the speedy responses, I have a much better understanding of this concept now. Also, I'll try to make my error messages more clear next time.
EDIT: updated with my newest code. the error happens on line 18. Also, I'm beginning to wonder if my latest issue has to do with the original class itself?
I'm trying to teach myself classes and objects in C++. I did it once by just declaring a void function, outputting something on the screen, calling the object in main and everything worked fine.
Now, I wanted to expand upon this and make a simple addition thing. However, I get a couple errors on Code Blocks:
error: invalid use of non-static member function 'int Addition::add(int, int)'
error: no matching function for call to 'Addition::add()'
Here's my code:
#include <iostream>
using namespace std;
class Addition {
public:
int add (int x, int y) {
int sum;
sum=x+y;
return sum;
}
};
int main()
{
int num1;
int num2;
int ans=addobj.add(num1,num2);
Addition addobj;
addobj.add(num1,num2);
cout<<"Enter the first number you want to add"<<endl;
cin>>num1;
cout<<"Enter the second number you want to add"<<endl;
cin>>num2;
cout<<"The sum is "<<ans<<endl;
}
One of the most important things, a developer should learn to do is to read compiler's messages. It's clear enough:
error: no matching function for call to 'Addition::add()'
Your function in your class is
int add (int x, int y)
it takes 2 arguments and you pass none:
addobj.add();
You have 2 options:
create and initialize x and y inside your main and pass them as arguments
make add without parameters, create x and y inside add's body, as their values are taken from user input.
In this case, as the function's name is add, I'd chose the first option:
declare int x, y; inside your main
read the user input inside the main (the part, where you use cin and cout)
pass the x and y as arguments to add like this: addobj.add( x, y );
store the result (if needed), like this: int result = addobj.add( x, y );
You declared a method add(int, int) that takes two integers as arguments; you have to supply those arguments when you call it. It would be nice to print the returned value, as well:
Addition addobj;
std::cout << addobj.add(1, 2) << std::endl;
Your add function takes two arguments, yet you call it with none, so no matching function could be found. You must call the function as it was declared, i.e.,
addobj.add(1, 2);
Your function takes two arguments and yet you call it without providing them. You need to provide the two integer arguments that your function requires. To be useful you should store the result too. Something like this
int a = 1;
int b = 2;
int result = addjobs.add(a,b);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
In this Program, I am unable to understand the declaration of the "sum" function.
Please explain what is happening while calling the sum function and while declaring the function.
#include<iostream.h>
#include <conio.h>
int sum(int(*)(int),int);
int square(int);
int cube(int);
void main()
{
clrscr();
cout<<sum(square,4)<<endl;
cout<<sum(cube,4)<<endl;
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i);
}
return s;
}
int square(int k)
{
int sq;
sq=k*k;
return k*k;
}
int cube(int k)
{
return k*k*k;
}
The parameter is a function pointer - you should read here for an introduction, and heres a relevant SO post.
The idea is that you can pass around a function as a value - so you can make other general functions that you can give a specific function to in order to change the effect. An example would be map from functional programming.
Specifically in your case, the sum function takes this function pointer in order to sum a function of the values in the list given to it, rather than just the values themselves. This is demonstrated by passing it eg. a pointer to the square function, which will make it sum squares of the values given to sum.
This is the reason why some people does not like pointers in C and C++. See my explanation below in your program:-
#include<iostream.h>
# include <conio.h>
void main()
{
clrscr();
int sum(int(*)(int),int);// Here first parameter in `sum` is a pointer to a function which return type is int. `int(*)(int)` here int(*) is function pointer and (int) is its parameter type.
int square(int);
int cube(int);
cout<<sum(square,4)<<endl;// Now you are passing address of function `square` as first parameter and its parameter 4, like square(4)
cout<<sum(cube,4)<<endl; // Here you are passing address of function `cube` as parameter and 4 as parameter to cube function
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i); //This `ptr` is nothing but the address of function passed to sum
//hence it execute like below
//When you are calling function `sum` with function pointer `square` as first parameter
//it execute like `s = s + square(i);`
//Now at the second call to `sum` it execute like `s = s + cube(i);`
}
return s;
}
// The method sum
// First argument: a pointer to a function which accepts one integer
// as argument and returns an integer
// Second argument: an integer
int sum(int(*)(int),int);
That is why when you call sum in this line:
cout<<sum(square,4)<<endl;
You pass square as the first argument and since square is like this:
int square(int k)
{
}
it satisfies the call because it is a function which accepts one integer as argument and returns int.
Then inside the sum method, it calls the function which you passed in as the first argument like this (please read my comments inline for clarity):
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
// Calls the function pointer (square in this case) and sends i to
// it as argument. It then takes the return value and adds it to s.
s+=(*ptr)(i);
}
return s;
}
Here are the different parts:
Here is another example to help you:
// fcnPtr is a pointer to a function that takes no arguments and returns an integer
int (*fcnPtr)();
Function Prototype
void GenerateSecretNumber(int rang, int x);
Function Declaration Definition
void GenerateSecretNumber(int rang, int x){
int secret = 0;
cout<<"Computer is calculating a random secret number in the given range ...";
srand(time(NULL));
secret = rand()%(rang+1);
cout<<"Done!"<<endl<<endl;
}
This definition is fine. The problem is when you're calling GenerateSecretNumber() function.
While calling, you need to pass the exact number of arguments. something like
int p = 5;
int q = 10;
and
GenerateSecretNumber(p, q);
However, I see no logical reason to pass and accept the second parameter x. :-) You never used it inside your function. You can consider redefining your function signature as void GenerateSecretNumber(int rang).
I'm suspecting, maybe, currently you used something like GenerateSecretNumber(p); only.
Very simple question:
I was fiddling with basic C++ (being very new to programming) and I got into trouble while declaring a global variable to do some addition
#include <iostream>
int x,y;
int sum(int, int)
{
return x + y;
}
int main()
{
using namespace std;
cout << "The sum of 10 and 4 is: " << sum(10,4) << endl;
return 0;
}
Changing "int x,y;" to "int x,y = 0" has the same result: The sum equates to 0.
Could someone explain this odd behavior? Thanks!
Your function always returns the sum of global variables x and y, which are always 0. x and y are implicitly set to zero at the program startup. You never change their values, so they remain zero forever. The sum of two zeros is zero, no surprise here.
You pass 10 and 4 to your function, but the function itself completely ignores what is passed to it, i.e. it ignores its parameters (they are not even named). It always sums global x and y, which are always 0.
If you want your function to sum its arguments, you have to name the function parameters and use them
int sum(int a, int b)
{
return a + b;
}
And now you don't need any global variables at all. (main remains as is.)
Alternatively, if you so desire, you can get rid of the parameters completely and sum the global variables instead
int x,y;
int sum()
{
return x + y;
}
but in this case you will have to pass the values to sum through those global variables, not as function arguments
int main()
{
using namespace std;
x = 10;
y = 4;
cout << "The sum of 10 and 4 is: " << sum() << endl;
return 0;
}
This latter approach is here just for illustrative purposes. It is definitely not a good programming practice.
What you have in your code is a weird disconnected hybrid of these two approaches, which can't possibly work.
In order to fix the issue, the thing requires changing is the sum function.
int sum(int a, int b){
return a+b; //a,b here are referring to the inputs, while what you did was referring to the global variable..
}
Besides, try not to use global variables, usually you would end up with lots of troubles.
Another thing, I don't think your way of defining a function is correct. The inputs have to look like this instead:
int sum(int a, int b)
Unless you wanna declare the function first and provide the actual implementation later, you are not suppose to miss the name of the inputs!
when you are just globally declare the variables x,y ,they implicitly set to zero value.in your function definition,you are just giving the datantype of args, not the args names.so when you returning the sum of x,y ,it returns zero.and the value passed by the main function goes nowhere.
your program must look like this
#include<iostream>
int x,y;
int sum(x,y)
{
return x+y;
}
int main()
{
int v,a,b;
cout<<"values of a and b";
cin>>a>>b;
v=sum(a,b)
cout<<"their sum is"<<v;
}
when you explicitly define the value in second case
i.e int x,y=0;
you are just explicitly giving the value of value y to 0 while the x implicitly remains 0 and since you are not giving the args name,the ultimately result return biy the function is zero,
Seems that you only need x and y inside your add function, so make them local to the function. There is no reason to make them global. Follow the "least accessibility" idiom to prevent other parts of your program from mistakenedly modifying variables.
You might need a global variable supposed you want to define a well known parameter that every function needs to know and yet modifiable during run time. If you want it fixed, then a global constant would be more proper.
Hope that helps.
I need your help to get started with a good implementation thinking.
I need to create a simple program with the following:
1. A function with two parameters, first parameter is a name (char*), and the second parameter is the number of times you would like to print this name to the screen(int).
If the second parameter wasn't supplied in the function call, it should print the name 10 times.
If the first parameter wasn't supplied in the function call, it should print the author name / the writer of the program (i.e my name).
I was thinking to create the following function with default parameteres:
void printTextToScreenNTimes(char * text = "guy", int n = 10);
This function implementation is the following :
void printTextToScreenNTimes(char * text, int n) {
int i;
for (i = 0; i < n; i++)
cout << text << " ";
}
My problem arises as I try to print my default name 2 times. For example if I want only using the following function call:
void printTextToScreenNTimes(3);
I would like the function to print the default name (in this case "guy") 3 times but It's impossible because I must fill the first parameter.
Do I have no choice but using a global parameter holding my name?
Overloading:
void printTextToScreenNTimes(int x)
{
printTextToScreeNTimes("guy", x);
}
I think you are reading too much into your requirements. I think the second part about not supplying the name only applies when the first part (not supplying the count) also applies.
But in any case you can solve it using overloading as Luchian has just explained.
I don't get how to use structs properly to achieve my goal of calculating Fractions (it is required). Quite frankly I don't have much of an idea of what I'm doing, this is only my 3rd class in C++ and I feel lost...this was the task assigned to us
Your enter() function accepts a fraction from the user. Your
simplify() function simplifies the fraction that it receives, if
possible. Your display() function displays the fraction that it
receives.
Your global functions use a Fraction type. A Fraction type holds the
numerator and denominator of a fraction as separate data members.
This is my program, only the main EXCEPT the "cin" and "cout" and the GCF function was provided by the professor, all other functions and struct outside of the main i tried to do myself...
#include <iostream>
using namespace std;
void entry (int a, int b);
void simplify (double c);
void display(int x, int y)
int main()
{
struct Fraction fraction;
cout << "Enter a numerator: " << endl;
cin >> fraction.num;
cout << "Enter a denominator: " << endl;
cin >> fraction.den;
cout << "Fraction Simplifier" << endl;
cout << "===================" << endl;
enter(&fraction);
simplify(&fraction);
display(fraction);
}
struct Fraction {
int num;
int den;
}
struct Fraction fraction{
fraction.num;
fraction.den;
}
void display(int num, int den) {
cout << fraction.num << endl;
cout << fraction.den << endl;
}
// Great Common Factor (Euclid's Algorithm), provided by Professor
int gcf( int num1, int num2 )
{
int remainder = num2 % num1;
if ( remainder != 0 )
{
return gcf( remainder,num1 );
}
return num1;
}
these are my errors:
w2.cpp: In function 'int main()':
w2.cpp: 14: error: aggregate 'Fraction fraction' has incomplete type and cannot be defined
w2.cpp: 23: error: 'enter' was not declared in this scope
w2.cpp: At global scope: w2.cpp:35: error: function definition does not declare parameters
w2.cpp: In function 'void display(int, int)':
w2.cpp: 41: error: 'fraction' was not declared in this scope
I'm sorry for the really long post, but any and all help is greatly appreciated.
AND if someone could point me to a helpful C++ book that I could read while at home and or in lectures (because of a language barrier i cannot understand my prof well enough) would also be appreciated
Let's walk through these:
error: aggregate 'Fraction fraction' has incomplete type and cannot be defined
Now, in main(), you said struct Fraction fraction;. At this point, you're forward-declaring your struct. It is not complete, so you can't use it as if it were.
You should have your whole Fraction struct defined before main(). Also note that the struct in struct Fraction fraction; is unnecessary, and left over from C.
error: 'enter' was not declared in this scope
Simple. You've declared entry() up top, but you're trying to use enter(). Not much more to be said.
At global scope: w2.cpp:35: error: function definition does not declare parameters
Now this is a bit more confusing. This is the offending line:
struct Fraction fraction{
How the compiler sees this is that it is a function returning a Fraction, but it's missing its parameter list. I'm not exactly sure what you're trying to do with this block of code.
error: 'fraction' was not declared in this scope
Looks like you're trying to use an object declared somewhere else. If you want the one from main(), you'll have to pass it in as an argument. If you want a global variable fraction, all you need in the global space is:
Fraction fraction;
This should occur after the Fraction struct. Also note that because this has the same object name as the one in main(), the one in main() shadows this one, and if you want to access the global one from main() you need to use ::fraction.
I hope that helps clear up some of the understanding.
Some other errors I see are:
enter(&fraction);
You're passing a Fraction * to a function that takes two ints. I think you'd want this one to take a Fraction &. Then you can just call it like enter (fraction); to have it modify the object passed in.
simplify(&fraction);
Similar, but this one takes a double. I think you'd want it to take a Fraction & as well.
Your entry and simplify functions never get defined, but you still try to use them.
display should take a Fraction in order to print the parts of it.
A list of recommended books on C++. Searching this site helps too.
In C++, structures (or classes) and unions form the two basic types of user defined data structure. A user defined data structure is a model/blue-print of something (it could be a real-world quantity or an abstract concept) you want your program to work with. So, if you wanted a structure to store your friends' names, you'd probably do something like this:
struct FriendName {
std::string first, last;
}; // the semi-colon is required here
first and last are the members of your struct. std::string is the type of these members which tells the compiler what sort of data you want to store -- the data here being strings we use the appropriate type defined by the library.
Once you've defined something called a FriendName you can use it to store data and also work with this data. However, if you try to define FriendName again, the compiler will complain. Which is what is happening with your code.
Now, in order to use this data structure, you will need to create an object (which is a region of memory that represents a particular FriendName instance). You can create an object as follows:
FriendName fred; // note that I don't need to use struct FriendName
and you can go ahead and use it as:
fred.first = "Fred"; // write 'fred' object's first name
fred.last = "Flintstone";
The object name works as a marker which when combined with with the . operator and a member name allows you to read/write that particular member.
Assume you wanted to read in the names from the console: In that case you'd do:
FriendName wilma;
std::cin >> wilma.first >> wilma.last; // read in 'wilma' objects members one by one
Now, there's enough up there to get you started!